package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Returns a date, given year and day-of-year columnValueList. dayofyear must be
 * greater than 0 or the result is NULL_KEY.
 *
 * <pre>
 * mysql> SELECT MAKEDATE(2011,31), MAKEDATE(2011,32);
 *         -> '2011-01-31', '2011-02-01'
 * mysql> SELECT MAKEDATE(2011,365), MAKEDATE(2014,365);
 *         -> '2011-12-31', '2014-12-31'
 * mysql> SELECT MAKEDATE(2011,0);
 *         -> NULL_KEY
 * </pre>
 */
public class Makedate extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        Integer year = Type.IntegerType.convert(args[0]);
        Integer dayOfYear = Type.IntegerType.convert(args[1]);
        if (dayOfYear <= 0) {
            return null;
        }

        Calendar cal = Calendar.getInstance();
        cal.set(year, 0, 0, 0, 0, 0);
        cal.set(Calendar.DAY_OF_YEAR, dayOfYear);
        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        return Type.DateType;
    }

    public String[] getFunctionNames() {
        return new String[]{"MAKEDATE"};
    }
}
